package com.example.controller;

import com.example.service.ExcelService;
import com.example.service.StudentService;
import com.example.service.SubjectService;
import com.example.utils.Msg;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * @author： wzz
 * @date： 2021-11-07 10:15
 */

@Controller
@Slf4j
@RequestMapping(value = "excelUpload/")
public class ExcelController {


    @Resource
    private StudentService studentService;
    @Resource
    private SubjectService subjectService;
    @Resource
    private ExcelService excelService;

    // excel导入
    private final static String utf8 ="utf-8";



    /**
     * 导入题目
     * @param request
     * @param response

     * @throws Exception
     */
    @PostMapping(value = "/importSubject/{book_name}/{menu_topic}")
    @ResponseBody
    public void importSubject(HttpServletRequest request, HttpServletResponse response,
                             @PathVariable(value = "book_name") String book_name,
                             @PathVariable(value = "menu_topic") String menu_topic) throws Exception {

        if (request instanceof MultipartHttpServletRequest) {
            System.out.println("error");
        }
        //分片
        response.setCharacterEncoding(utf8);
        Integer schunk = null;
        Integer schunks = null;
        String name = null;
        String lastModifiedDate = null;
        String temFileName = null;
        String uploadPath = System.getProperty("user.dir")+"/static/opt/word";
        BufferedOutputStream os = null;
        try{
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(1024);
            factory.setRepository(new File(uploadPath));
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setFileSizeMax(5L *1024L *1024L* 1024L);
            upload.setSizeMax(10L *1024L *1024L*1024L);
            List<FileItem> items = upload.parseRequest(request);

            for(FileItem item : items){
                if(item.isFormField()){
//                    分片数
                    if("chunk".equals(item.getFieldName())){
                        schunk = Integer.parseInt(item.getString(utf8));
                    }
//                    总分片数
                    if("chunks".equals(item.getFieldName())){
                        schunks = Integer.parseInt(item.getString(utf8));
                    }
//                    文件名：根据时间戳命名,恰好文件存储了存进去的时间
                    if("name".equals(item.getFieldName())){
                        name = item.getString(utf8);

                    }
                    if ("lastModifiedDate".equals(item.getFieldName())){
                        lastModifiedDate = item.getString(utf8);
                        int i=name.lastIndexOf(".");
                        temFileName = lastModifiedDate +name.substring(i);
                    }
                }
            }

            for(FileItem item : items){
                if(!item.isFormField()){
//                    String temFileName = name;   //未分片的话文件名就是原名

                    if(name != null){   //文件名不能为空
                        if(schunk != null){   //分片数目
                            temFileName = schunk +"_"+name;   //分片的话文件名就是这个
                        }
                        File temFile = new File(uploadPath,temFileName);
                        if(!temFile.exists()){//断点续传
                            item.write(temFile);
                        }
                    }
                }
            }

            //文件合并
            if(schunk != null && schunk.intValue() == schunks.intValue()-1){

                //命名规定为时间戳

                File tempFile = new File(uploadPath,temFileName);
                os = new BufferedOutputStream(new FileOutputStream(tempFile));


                for(int i=0 ;i<schunks;i++){
                    File file = new File(uploadPath,i+"_"+name);
                    while(!file.exists()){
                        Thread.sleep(100);
                    }
                    byte[] bytes = FileUtils.readFileToByteArray(file);
                    os.write(bytes);
                    os.flush();
                    file.delete();
                }
                os.flush();
            }

            File file = new File(uploadPath,temFileName);

            excelService.Import(file,book_name,menu_topic);


            response.getWriter().write("导入成功"+name);

        }finally {
            try{
                if(os != null){
                    os.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

    @ResponseBody
    @PostMapping("/importStudent")
    public Msg ImportStudent(MultipartFile file) throws IOException {

        if(studentService.importStudent(file)==0){
            return Msg.fail();
        }
        return Msg.success();
    }
}
